package com.example.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
//import cn.hutool.json.ObjectMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.entity.User;
import com.example.service.IUserService;
import com.example.service.QRService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 患者用户 前端控制器
 * </p>
 *
 * @author wyx
 * @since 2025-03-10
 */
@RestController
@RequestMapping("/user")
@CrossOrigin//跨域访问
@Slf4j
@Api(tags = "患者用户管理模块")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    QRService qrService;
    QrConfig config = new QrConfig();
    ObjectMapper json = new ObjectMapper();



    @ApiOperation(value = "分页展示用户列表")
    @GetMapping("/getusers")
    public R userlist(@RequestParam(defaultValue = "1") int page, // 当前页码，默认值为1
                      @RequestParam(defaultValue = "5") int pageSize,
                      @RequestParam(required = false, defaultValue = "") String name) { // 每页大小，默认值为10
        log.info("获取用户列表，页码：{}，每页大小：{}", page, pageSize);

        // 创建分页对象
        Page<User> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (!name.isEmpty()){
            queryWrapper.like(User::getName, name);
        }

        // 执行分页查询
        Page<User> result = userService.page(pageInfo, queryWrapper);

        // 返回分页结果
        return R.success(result);
    }


    //根据id查询用户
    @GetMapping("/selectById")
    public Map<String, Object> userget(@RequestParam Integer id) {
        log.info("获取用户{}", id);
        User user = userService.getById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        return result;
    }

    //新增用户
    @PostMapping("/adduser")
    public R<String> useradd( User user) {
        log.info("新增用户{}", user);
        Boolean flag = userService.save(user);
        if (flag) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    //删除用户
    @DeleteMapping("/deleteuser/{id}")
    public R<String> userdelete(@PathVariable("id") Integer id) {
        log.info("删除用户{}", id);
        Boolean flag = userService.removeById(id);
        if (flag) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    //   修改用户
    @PutMapping("/updateuser")
    public R<String> userupdate(User user) {
        log.info("修改用户{}", user);
        Boolean flag = userService.updateById(user);
        if (flag) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }
    }

    //用户注册
    @PostMapping("/register")
    public Map<String, Object> register( User user) {
        log.info("用户注册{}", user);
        Map<String, Object> R = new HashMap<>();
        Boolean flag = userService.save(user);

        if (flag) {
            R.put("flag", true);
        } else {
            R.put("flag", false);
            R.put("message", "注册失败！");
        }
        return R;
    }

    //用户登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String phone,
                        @RequestParam String password,
                        HttpSession httpSession) {

        log.info("用户登录，手机号：{}，密码：{}", phone, password);
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone).eq(User::getPassword, password);
        User user = userService.getOne(queryWrapper);

        // 返回结果
        Map<String, Object> R = new HashMap<>();
        if (user != null) {
            R.put("flag", true);
            R.put("role", "user"); // 返回用户角色信息
            R.put("user", user);
            httpSession.setAttribute("user", user.getId()); // 将用户ID存入Session
        } else {
            R.put("flag", false);
            R.put("message", "用户名或密码错误"); // 返回错误信息
        }
        log.info("R:{}", R.toString());
        return R; // 返回JSON对象
    }

    //生成二维码
    @GetMapping("/code")
    public void generateUserCode(Integer userid, HttpServletResponse response) throws Exception {
        log.info("生成二维码id:{}", userid);
        User user =this.userService.getById(userid);
        if(user.getQrcode()==1){
            config.setBackColor(Color.green.getRGB());
        }else if(user.getQrcode()==2){
            config.setBackColor(Color.yellow.getRGB());
        }else {
            config.setBackColor(Color.red.getRGB());
        }
        QrCodeUtil.generate(json.writeValueAsString(user), config, "png", response.getOutputStream());
    }
}
